package com.xie.smfs.entity;

import net.minecraft.block.ChestBlock;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.damage.DamageType;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.entity.player.PlayerEntity;
import net.fabricmc.fabric.api.event.player.UseBlockCallback;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import net.minecraft.entity.attribute.DefaultAttributeContainer;
import net.minecraft.entity.LivingEntity;
import net.minecraft.screen.ScreenHandler;

public class BoxGhostEntity extends GhostEntity {
    public static DefaultAttributeContainer.Builder createLivingAttributes() {
        return LivingEntity.createLivingAttributes()
                .add(EntityAttributes.GENERIC_MAX_HEALTH, 20.0)
                .add(EntityAttributes.GENERIC_MOVEMENT_SPEED, 0.25)
                .add(EntityAttributes.GENERIC_ATTACK_DAMAGE, 5.0);
    }

    private static final boolean HAS_GHOST_DOMAIN = true; // 0级鬼域
    private static final int GHOST_DOMAIN_LEVEL = 0;
    private static final double GHOST_DOMAIN_RADIUS = 32.0;
    private static final char TERROR_LEVEL = 'C'; // C级

    // 攻击冷却时间，防止连续攻击
    private int attackCooldown = 0;

    public BoxGhostEntity(EntityType<? extends GhostEntity> entityType, World world) {
        super(entityType, world, HAS_GHOST_DOMAIN, GHOST_DOMAIN_LEVEL, GHOST_DOMAIN_RADIUS, TERROR_LEVEL);
        Objects.requireNonNull(this.getAttributeInstance(EntityAttributes.GENERIC_MAX_HEALTH)).setBaseValue(20.0);
        Objects.requireNonNull(this.getAttributeInstance(EntityAttributes.GENERIC_MOVEMENT_SPEED)).setBaseValue(0.25);
        Objects.requireNonNull(this.getAttributeInstance(EntityAttributes.GENERIC_ATTACK_DAMAGE)).setBaseValue(5.0);
    }

    @Override
    protected boolean shouldAttackPlayer(PlayerEntity player) {
        // 检查攻击冷却
        if (attackCooldown > 0) {
            return false;
        }

        // 检查玩家是否在范围内
        // 检测玩家是否正在与箱子交互
        return isPlayerInteractingWithChest(player);
    }

    // 检查玩家是否在攻击范围内
    private boolean isPlayerInRange(PlayerEntity player) {
        return this.squaredDistanceTo(player) <= GHOST_DOMAIN_RADIUS * GHOST_DOMAIN_RADIUS; // 鬼域范围内
    }

    // 检测玩家是否正在与箱子交互
    // 记录玩家最近打开箱子的时间
    private static final Map<UUID, Long> playerChestInteractionMap = new HashMap<>();
    private static final int INTERACTION_TIMEOUT = 50; // 50 tick (2.5秒)内视为正在交互

    // 监听玩家交互箱子事件
    public static void registerChestInteractionListener() {
        UseBlockCallback.EVENT.register((player, world, hand, hitResult) -> {
            if (!world.isClient() && world.getBlockState(hitResult.getBlockPos()).getBlock() instanceof ChestBlock) {
                playerChestInteractionMap.put(player.getUuid(), System.currentTimeMillis());
            }
            return ActionResult.PASS;
        });
    }

    private boolean isPlayerInteractingWithChest(PlayerEntity player) {
        // 检查玩家是否在交互超时时间内打开过箱子
        Long lastInteractionTime = playerChestInteractionMap.get(player.getUuid());
        if (lastInteractionTime == null) return false;
        return (System.currentTimeMillis() - lastInteractionTime) < INTERACTION_TIMEOUT * 50; // 将tick转换为毫秒
    }

    @Override
    public void tick() {
        super.tick();

        // 减少攻击冷却
        if (attackCooldown > 0) {
            attackCooldown--;
        }

        // 服务器端逻辑
        if (!this.getWorld().isClient()) {
            // 每10 tick检查一次附近的玩家
            if (this.age % 10 == 0) {
                for (PlayerEntity player : this.getWorld().getPlayers()) {
                    if (this.shouldAttackPlayer(player) && this.canSee(player)) {
                        this.executeAttack(player);
                        attackCooldown = 40; // 2秒冷却
                        break; // 一次只攻击一个玩家
                    }
                }
            }
        }
    }

    @Override
    protected void executeAttack(PlayerEntity player) {
        // 瞬移到玩家面前
        this.teleport(player.getX(), player.getY(), player.getZ());
        // 获取 mob 伤害类型的注册表项
        RegistryEntry<DamageType> mobDamageType = this.getWorld().getRegistryManager().get(RegistryKeys.DAMAGE_TYPE).getEntry(RegistryKey.of(RegistryKeys.DAMAGE_TYPE, new Identifier("smfs", "ghost"))).orElseThrow(() -> new IllegalStateException("MOB_ATTACK damage type not found"));
        // 创建伤害源
        DamageSource damageSource = new DamageSource(mobDamageType, this);
        player.addStatusEffect(new StatusEffectInstance(StatusEffects.WEAKNESS, 20, 1));

        player.damage(damageSource, 100.0f);
    }
}